<script lang="tsx">
import {
  defineComponent,
  ref,
  computed,
  type ExtractPropTypes,
  type PropType,
  unref,
  inject
} from 'vue'
import { ElButton } from 'element-plus'
import oFormFactory, { oFormProps, type iFormColumnType } from '../form/factory.vue'
import { merge } from 'lodash-es'
import { $AONE_LAN, type SimpleKeyValueObject } from '../form/utils'

export interface iSearchOptionsProps {
  columns: Array<iFormColumnType>
  title?: string
  search?: boolean
  reset?: boolean
  excel?: boolean
  autoreload?: boolean
}
export const oSearchProps = {
  searchOptions: {
    required: true,
    type: Object as PropType<iSearchOptionsProps>
  }
}
export type oFormPropsType = ExtractPropTypes<typeof oSearchProps>
export default defineComponent({
  components: { oFormFactory },
  props: oSearchProps,
  setup(props: oFormPropsType, context) {
    const refOForm = ref()
    const formData = inject<SimpleKeyValueObject>('formData')! // 感叹号是一定存在
    const eventData = inject<SimpleKeyValueObject>('eventData')! // 感叹号是一定存在
    const mergeButton = (name: string, config?: iFormColumnType) => {
      return {
        comtype: 'button',
        className: `one-button-${name}`,
        label: Reflect.get($AONE_LAN, name),
        labelWidth: '0px',
        type: config?.type,
        onClick: config?.onClick
      }
    }
    const buttonCallbackMap = new Map<string, iFormColumnType>()
    // 只显示这三种按钮：搜索、重置、导出excel
    new Array('search', 'reset', 'excel').forEach((eventName: string) => {
      const typeMap = new Map<string, string>([
        ['search', 'danger'],
        ['reset', 'warning'],
        ['excel', 'success']
      ])
      buttonCallbackMap.set(eventName, {
        type: typeMap.get(eventName),
        onClick: () => {
          // 其他组件watch事件
          eventData[eventName] = true
        }
      })
    })
    const searchOptionsSync = computed(() => {
      const searchOptions = merge(
        {
          inline: true,
          columns: new Array<iFormColumnType>(),
          title: '',
          ...Array.from(buttonCallbackMap.keys()).reduce((p: SimpleKeyValueObject, c: string) => {
            p[c] = true
            return p
          }, {})
        },
        unref(props.searchOptions)
      )
      // 按钮区域
      for (let entry of buttonCallbackMap.entries()) {
        const [name, config] = entry
        if (Reflect.get(searchOptions, name)) {
          searchOptions.columns.push(mergeButton(name, config))
        }
      }
      // form-item 样式
      searchOptions.columns.forEach((colItem) => {
        colItem.formItemClassName = 'one-nopadding'
      })
      return searchOptions
    })
    return () => (
      <section class="one-search">
        <oFormFactory ref={refOForm} formOptions={searchOptionsSync} />
      </section>
    )
  }
})
</script>
<style lang="scss" scoped>
section {
  background: #f9f9fa;
  box-sizing: border-box;
}
</style>
